package com.zyj.test.month1.day12;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author Yijia Zhang
 * @create 2024-05-30 00:11
 */
public class code2982 {
    //遍历一遍 贪心算法
    public int maximumLength(String s) {
        int len = s.length();
        if (len < 3) {
            return -1;
        }
        List<List<Integer>> list = new ArrayList<>();
        for (int i = 0; i < 26; i++) {
            list.add(new ArrayList<>());
        }

        int idx = 0;
        int tmp = 0;
        char pre = ' ';
        while (idx < len) {
            char c = s.charAt(idx);
            if (c == pre) {
                tmp++;
            } else {
                if (pre != ' ') {
                    list.get(pre - 'a').add(tmp);
                }
                tmp = 1;
            }
            pre = c;
            idx++;
        }
        list.get(pre - 'a').add(tmp);
        int res = 0;
        for (int i = 0; i < 26; i++) {
            List<Integer> l = list.get(i);
            if (l.size() > 0) {
                Collections.sort(l, (i1, i2) -> -Integer.compare(i1, i2));
                int max = l.get(0);
                res = Math.max(res, max - 2);
                if (l.size() > 1 && l.get(1) >= max - 1) {
                    res = Math.max(res, max - 1);
                }
                if (l.size() > 2 && l.get(1) >= max && l.get(2) >= max) {
                    res = Math.max(res, max);
                }
            }

        }
        return res <= 0 ? -1 : res;
    }
}
